package ide.ccf.ccproject.data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ide.ccf.ccproject.common.Utils;
import ide.ccf.ccproject.translate.Message;
import ide.ccf.ccproject.wizards.pages.ExportSelectFolderWizardPage;
import ide.ccf.ccproject.wizards.pages.ExportSetInfoWizardPage;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Shell;

public class GenerateCPK{
	protected static Shell shell;  
	private Document document;
	static Thread thread;
	static Display display = Display.getDefault();
	public static Text tips;
	public static String output;
	static boolean stop;
	static boolean flag;
	static Button bClose;
	public GenerateCPK(Shell parent) {
		output= "";
		stop = false;
		flag = true;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            this.document = builder.newDocument();
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        }
	}
	
	 public static void open() { 
	        createContents();  
	        shell.open();  
	        shell.layout();   
	    }
	 
		private static void createContents() {
		    shell = new Shell(display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);  
	        shell.setSize(500, 300);  
	        shell.setText("导出CPK包");  
	        shell.setLayout(new FillLayout());
	        Composite c = new Composite(shell, SWT.NONE);
	        GridLayout layout = new GridLayout();
			layout.numColumns = 1;
			layout.verticalSpacing = 15;
			c.setLayout(layout);
			
	        tips  = new Text(c, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY);
	        GridData gd_labelText = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
	        gd_labelText.heightHint = 200;
	        tips.setLayoutData(gd_labelText);
	        tips.setText("");     
	        tips.setTopIndex(Integer.MAX_VALUE); 
/*		    ProgressBar hBar = new ProgressBar(c, SWT.HORIZONTAL
					| SWT.INDETERMINATE);
			hBar.setMinimum(0);
			hBar.setMaximum(100);
	        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 3, 1);
	        gd.widthHint = 400;
	        hBar.setLayoutData(gd);*/
	        tips.setLayoutData(gd_labelText);
	        
	        Composite c_ = new Composite(c, SWT.NONE);
	        GridLayout layout_ = new GridLayout();
	        layout_.numColumns = 2;
	        layout_.verticalSpacing = 15;
			c_.setLayout(layout_);
			Label occupy = new Label(c_, SWT.NONE);
		    GridData gd1 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
		    gd1.widthHint = 180;
		    occupy.setLayoutData(gd1);
	        bClose = new Button(c_, SWT.PUSH);
	        bClose.setText("确　定");
	        //bClose.setSize(200, SWT.DEFAULT);
	        bClose.setEnabled(false);
		     GridData gd2 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
		     gd2.widthHint = 100;
		     bClose.setLayoutData(gd2);
	        bClose.addSelectionListener(new SelectionAdapter(){
	        	@Override
				public void widgetSelected(SelectionEvent e) {
					close();
				}
	        });
	}

		public static void close(){		 
			 while (!shell.isDisposed()) {
				 shell.close();
		            if (!display.readAndDispatch())
		                display.sleep();
		        }
		 }
			
		public static void callCmd(String cmd) throws InterruptedException, IOException {
            // 使用Runtime来执行command，生成Process对象
            Process process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd });
             //process.waitFor();
            // 取得命令结果的输出流
            InputStream in = process.getInputStream();
            // 用一个读输出流类去读
            InputStreamReader isr = new InputStreamReader(in);
            // 用缓冲器读行
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            StringBuilder sb = new StringBuilder();
            System.out.println("[stop:]"+stop);
            System.out.println("br.readLine():"+br.readLine());
            if(br.readLine() == null)
            	output +="cpkg打包失败,请检测是否已经安装cpkg命令!";
            while ((line = br.readLine()) != null && !stop) {
            	 //System.out.println("line："+ line);
            	// System.out.println("stop"+ stop);
                output +="正在导出：" + line + "\r\n";   
                sb.append(line);
            } 
            //System.out.println("【end】");
	        stop = true;  
	        thread = null;
            in.close();
            isr.close();
            br.close();
            display.asyncExec(new Runnable() {  
				public void run() {  
				   if(!bClose.isDisposed())
			        	bClose.setEnabled(true);
            }});

    }
		
		public void performFinish()
		{
			//拷贝files里面的exports文件到ccf/exports里面，以便安装进沙箱，系统自动识别。
			String ccfpath = ExportSelectFolderWizardPage.ccffoldername.getText().trim();
			String filesExports = ExportSelectFolderWizardPage.exportPath;
			String outExports = ExportSelectFolderWizardPage.sfoldernamePath_cache + ccfpath + "/exports";
			Utils.copyFolder(filesExports, outExports);
			//提升sfoldernamePath_cache目录下文件的权限s
			Utils.runCommand("chmod -R 777 " + ExportSelectFolderWizardPage.sfoldernamePath_cache, 0);
			//------------------------------------------------------------------- 拼接cpk包的格式----------------------------------------------------------------------------------------
			String strSFolder = ExportSelectFolderWizardPage.sfoldernamePath_cache + "/CPK/control.xml";
			String name = SetControlXml.parserXml(strSFolder, "name");
			//判断name有空格的情况
			if(name.contains(" "))
			{
				 String a[] = name.split(" "); 
				 name = a[0];
			}
			name = name.toLowerCase();
			String version = SetControlXml.parserXml(strSFolder, "version");
			String arch = SetControlXml.parserXml(strSFolder, "architecture");
			String StrCpk = ExportSelectFolderWizardPage.foldername.getText().trim() + "/" + name + "_" + version + "_" + arch + ".cpk";
			//------------------------------------------------------------------------------- END-----------------------------------------------------------------------------------------------
			System.out.println(StrCpk);
			//如果完成，则进行cpk打包操作。
			final String strCmd = ("cpkg  --pack   %1  %2").replace("%1", ExportSelectFolderWizardPage.sfoldernamePath_cache).replace("%2", StrCpk);
			System.out.println(strCmd);
			open();
			output += strCmd + "\r\n" + "正在导出 ..." + "\r\n" ;
	  	    tips.setText(output);
			thread = new Thread(new Runnable() {  
				public void run() {  
					while (flag) {  
						try {
							//System.out.println("is coming?");
							callCmd(strCmd);
						} catch (InterruptedException e1) {
							// TODO 自动生成的 catch 块
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO 自动生成的 catch 块
							e1.printStackTrace();
						}
						System.out.println("stop:"+ stop);
						 if(stop)
						{
								//System.out.println("线程停止！");
								flag = false; 
								display.asyncExec(new Runnable() {  
								public void run() {
									tips.setText(output);
				            }}); 
								break;
						}
					}  
				}  
			});  
			thread.start();
		}
}
